<template>
	<div>
		<div class="container">
			<h2 style="text-align: center;">（商品）砼申请单</h2>
			<div class="toolbar">
				<a-form ref="searchRef" :model="searchState" @finish="current = 1; loading = true; initData()">
					<a-row :gutter="20">
						<a-col :span="8">
							<a-form-item label="城市公司/专业公司">
								<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择城市公司/专业公司" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="选择项目">
								<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="innerProjectOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="申请编号">
								<a-input v-model:value="searchState.code" placeholder="请输入编号" allow-clear></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-space>
								<a-button type="primary" html-type="submit">
									<search-outlined />搜索
								</a-button>
								<a-button v-permission="171" type="primary" danger @click="addShangtong()">
									<plus-outlined />创建新计划
								</a-button>
							</a-space>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="mt-2">
				<!--
				v-if="!loading"使得:default-expand-all-rows="true"生效
				-->
				<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="shangtongSource" :pagination="pagination" :loading="loading" :row-class-name="(record, index) => (record.is_invalid === 1 ? 'table-striped' : null)" @change="initData">
					<template #bodyCell="{ column, record }">
						<template v-if="column.key === 'operation'">
							<a-space>
								<a-button v-permission="113" type="link" @click="showShangtong(record)">
									<diff-outlined />查看
								</a-button>
								<template v-if="![0,1,2].includes(record.workflow_status)">
									<a-button v-permission="114" type="link" @click="editShangtong(record)">
										<edit-outlined />修改
									</a-button>
									<a-button v-permission="115" type="link" style="color:#ff7875" @click="deleteShangtong(record.id)">
										<delete-outlined />删除
									</a-button>
								</template>
								<a-button v-if="record.workflow_status === 2 && record.purchase_quantity === 0 && !record.is_invalid" v-permission="114" type="link" style="color:#ff7875" @click="nullifyPurchase(record.id)">
									<PoweroffOutlined />作废
								</a-button>
							</a-space>
						</template>
						<template v-else-if="column.dataIndex === 'workflow_status'">
							<div>
								<a-workflow type="status" module="shangtong" :status="record.workflow_status" />
							</div>
						</template>
					</template>
				</a-table>
			</div>
		</div>
		<a-modal v-model:visible="visible" :footer="disabled ? null : undefined" :width="1200" :title="modalTitle" @ok="saveShangtong">
			<a-form ref="formRef" :model="formState" v-bind="{ labelCol: { style: { width: '180px' } } }">
				<table cellspacing="0" cellpadding="0" style="width: 100%;">
					<tr>
						<td>
							<a-form-item label="选择项目" name="project_id" :rules="{ required: true, message: '请选择项目' }">
								<a-select v-model:value="formState.project_id" :disabled="disabled" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" allow-clear @change="changeProject"></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="工号" name="use_position" :rules="{ required: true, message: '请选择工号' }">
								<a-row :gutter="10">
									<a-col :span="24">
										<a-tree-select v-model:value="formState.use_position" :dropdown-match-select-width="false" :show-search="true" placeholder="请选择工号" allow-clear tree-default-expand-all :tree-data="gonghaoTree" tree-node-filter-prop="label" style="width:100%" :disabled="disabled">
											<template #title="{ label }">{{ label }}</template>
										</a-tree-select>
									</a-col>
								</a-row>
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="砼标号（类别）" name="type" :rules="{ required: true, message: '请输入砼标号（类别）' }">
								<!-- <a-input v-model:value="formState.type" :disabled="disabled" /> -->
								<a-select v-model:value="formState.type" :disabled="disabled" :show-search="true" placeholder="请选择" :options="modelOptions" allow-clear :field-names="{ value: 'id', label: 'model' }" style="width:100%" @change="changeType(formState)"></a-select>
							</a-form-item>
						</td>
						<td>
							<a-form-item label="预计浇筑部位" name="expected_location" :rules="{ required: true, message: '请输入预计浇筑部位' }">
								<a-input v-model:value="formState.expected_location" placeholder="请输入预计浇筑部位" :disabled="disabled" />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="是否泵送（长度）" name="changdu" :rules="{ required: true, message: '请输入是否泵送（长度）' }">
								<a-input v-model:value="formState.changdu" :disabled="disabled" />
							</a-form-item>
						</td>
						<td>
							<a-row>
								<a-col :span="18">
									<a-form-item label="预计浇筑方量（m3）" name="fangliang" :rules="{ required: true, validator: validateFangliang, trigger: 'change' }">
										<a-input v-model:value="formState.fangliang" :disabled="disabled" @change="changeFangliang(formState)" />
									</a-form-item>
								</a-col>
								<a-col :span="6" style="padding: 5px 20px">合同余量：{{ formState.contractQuantity || 0 }}</a-col>
							</a-row>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="现场联系人" name="contacts" :rules="{ required: true, message: '请输入现场联系人' }">
								<a-input v-model:value="formState.contacts" :disabled="disabled" />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="申请塌落度（mm）" name="luodu" :rules="{ required: true, message: '请输入申请塌落度（mm）' }">
								<a-input v-model:value="formState.luodu" :disabled="disabled" />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="预计浇筑日期" name="add_time" :rules="{ required: true, message: '请输入预计浇筑日期' }">
								<a-date-picker v-model:value="formState.add_time" :disabled="disabled" value-format="YYYY-MM-DD HH:mm:ss" show-time />
							</a-form-item>
						</td>
						<td>
							<a-form-item label="现场联系电话" name="tel" :rules="{ required: true, message: '请输入现场联系电话' }">
								<a-input v-model:value="formState.tel" :disabled="disabled" />
							</a-form-item>
						</td>
					</tr>
					<tr>
						<td>
							<a-form-item label="备注" name="memo">
								<a-input v-model:value="formState.memo" placeholder="备注" :disabled="disabled" />
							</a-form-item>
						</td>
					</tr>
				</table>
			</a-form>
			<template #footer>
				<a-button type="plain" @click="visible = false">取消</a-button>
				<a-button type="primary" @click="saveShangtong">确定</a-button>
				<a-button class="cache-btn" @click="handleCache">
					<DeliveredProcedureOutlined />暂存
				</a-button>
			</template>
		</a-modal>
	</div>
</template>

<script setup>
import { reactive, ref, computed, getCurrentInstance, onMounted } from "vue";

import dayjs from "dayjs";

import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, DeliveredProcedureOutlined, DiffOutlined, PoweroffOutlined } from "@ant-design/icons-vue";

import { post, treeToList } from "../utils";

import { usePagination } from "vue-request";
import { add, subtract } from "@/utils/operation.js";
import { AWorkflow } from "@/components/index.js";
import { useRoute, useRouter } from "vue-router";

//缓存数据
const handleCache = () => {
	localStorage.setItem("shangtong-save", JSON.stringify(formState.value));
	proxy.$message.success("缓存成功");
};

const router = useRouter();
const searchRef = ref();
const searchState = reactive({});
const visible = ref(false);
const formState = ref({});
const gonghaoTree = ref([]);
const route = useRoute();
const query = route.query;

const disabled = ref(false);
const columns = [
	{
		title: "序号",
		dataIndex: "id",
		key: "id",
		align: "left",
		fixed: "left",
		width: 80,
	},
	{
		title: "编号",
		dataIndex: "code",
		sorter: false,
		width: 140,
		fixed: "left"
	},
	{
		title: "项目名称",
		dataIndex: "project",
		sorter: false,
		width: 130,
		customRender: ({ text, record, index, column }) => {
			return text?.name;
		}
	},
	{
		title: "工号",
		dataIndex: "part",
		sorter: false,
		width: 60,
		customRender: ({ text, record, index, column }) => {
			return (record.gonghao?.name || "") + (record.partInfo?.name || "");
		}
	},
	{
		title: "预计浇筑部位",
		dataIndex: "expected_location",
		sorter: false,
		width: 180,
	},
	{
		title: "砼标号（类别）",
		dataIndex: "type",
		sorter: false,
		width: 70,
	},
	{
		title: "预计浇筑方量（m3）",
		dataIndex: "fangliang",
		width: 120,
		sorter: false,
	},
	{
		title: "预计浇筑日期",
		dataIndex: "add_time",
		sorter: false,
		width: 100,
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD");
		}
	},
	{
		title: "现场联系人",
		dataIndex: "contacts",
		width: 80,
		sorter: false,
	},
	{
		title: "申请人",
		dataIndex: "applier",
		width: 60,
		customRender: ({ text, record, index, column }) => {
			return text.fullname || text.username;
		}
	},
	{
		title: "申请时间",
		dataIndex: "update_time",
		width: 100,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD");
		}
	},
	{
		title: "采购状态",
		dataIndex: "purchase_Surplus_quantity",
		sorter: false,
		width: 80,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text > 0 ? "采购未完成" : "采购完成";
		}
	},
	{
		title: "状态",
		dataIndex: "workflow_status",
		width: 60,
		sorter: false,
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 200,
		align: "center"
	}
];
const validateFangliang = async (_rule, value) => {
	if (!value) {
		return Promise.reject("请输入预计浇筑方量（m3）");
	}
	if (isNaN(Number(value))) {
		return Promise.reject("只能输入数字");
	}
	return Promise.resolve();
};
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));
const { data, loading, run, current, pageSize, total } = usePagination(async params => {
	const search = {};
	if (!projectOptions.value.length) await getProjects();
	if (searchState.company_id) {
		search.project_ids = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		}).map(item => item.value).join(',');
		if (!search.project_ids) {
			return [];
		}
	}
	return post("shangtong", { ...params, ...searchState, ...search })
}, {
	defaultParams: [
		{
			page_size: 20
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});
const projectOptions = ref([]);
const companyOptions = ref([]);
const getProjects = async () => {
	const projectResult = await post("department/projects?type=3", { page_size: 1000 });
	projectOptions.value = projectResult.data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
		};
	});
};
if (!projectOptions.value.length) {
	getProjects();
}
post("department/projects?type=2", {
	parent_ids: JSON.stringify([78, 24]),
}).then(({ data }) => {
	companyOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const innerProjectOptions = computed(() => {
	let options = [];
	if (!projectOptions.value.length) return options;
	if (searchState.company_id) {
		options = projectOptions.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		})
	} else {
		options = projectOptions.value;
	}
	if (!options.filter(item => item.value === searchState.project_id).length) {
		searchState.project_id = null;
	}
	return options;
})
const shangtongSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		return d;
	})
);
const addShangtong = () => {
	// optType.value = 1;
	// disabled.value = false;
	// formRef.value?.clearValidate();
	// visible.value = true;
	// const cacheData = localStorage.getItem("shangtong-save");
	// formState.value = JSON.parse(cacheData) || {};
	router.push(`shangtong/create`);
};
const editShangtong = async record => {
	// optType.value = 2;
	// formState.value = { ...record };
	// await changeProject(record.project_id);
	// visible.value = true;
	// disabled.value = false;
	// await getContractQuantity(formState.value);
	router.push(`shangtong/edit/${record.id}`);
};
const showShangtong = async record => {
	// optType.value = 3;
	// visible.value = true;
	// disabled.value = true;
	// formState.value = { ...record };
	// await changeProject(record.project_id);
	// await getContractQuantity(formState.value);
	router.push(`shangtong/info/${record.id}`);
};

const modelOptions = ref([]);
const contractlist = ref([]);
const contractInfo = ref({});
const optType = ref(1); // 1新增 2编辑 3查看
const changeProject = project_id => {
	const getDepartmentTree = () => {
		return new Promise((resolve, reject) => {
			// 更新工号下拉
			post("department/getTrees", { type: 4, parent_id: project_id }).then(data => {
				gonghaoTree.value = data;
				const gonghaoList = treeToList(JSON.parse(JSON.stringify(data)), []);
				if (!formState.value.use_position && (formState.value.gonghao_id || formState.value.part)) {
					const use_position = gonghaoList.filter(i => {
						return i.id === (formState.value.part || formState.value.gonghao_id);
					})[0];
					formState.value.use_position = use_position.value;
				} else {
					formState.value.use_position = null;
					formState.value.gonghao_id = null;
					formState.value.part = null;
				}
				resolve();
			});
		});
	};
	const getContractAll = () => {
		return new Promise((resolve, reject) => {
			// 主要材料/混凝土专项合同
			post("contract/all", { project_id: project_id, types: "1", material_type: 2 }).then(data => {
				modelOptions.value = [];
				contractlist.value = [];
				contractInfo.value = {};

				if (!data.length) {
					proxy.$message.error("当前项目尚未绑定合同");
					resolve();
				}

				contractlist.value = data;
				// 按照物资维度统计
				const materials = data
					.map(item => item.materials)
					.reduce((res, curr) => {
						res.push(...curr);
						return res;
					}, []);
				contractInfo.value = materials.reduce((res, curr) => {
					if (!res[curr.id]) {
						res[curr.id] = {
							model: curr.attr ? `${curr.model}（${curr.attr}）` : curr.model,
							quantity: 0
						};
					}
					const quantity = Number(curr.ContractMaterial.quantity);
					res[curr.id].quantity += isNaN(quantity) ? 0 : quantity;
					return res;
				}, {});
				modelOptions.value = Object.keys(contractInfo.value).map(key => {
					return {
						model: contractInfo.value[key].model,
						id: key
					};
				});

				// 编辑初始化处理
				if (optType.value === 2) {
					const type = formState.value.type;
					const target = Object.keys(contractInfo.value).find(key => contractInfo.value[key].model === type);
					formState.value.type = target || undefined;
				}
				resolve();
			});
		});
	};
	return Promise.all([getDepartmentTree(), getContractAll()]);
};

const changeType = async record => {
	record.contractQuantity = 0;
	record.fangliang = null;
	await getContractQuantity(record);
};
const getContractQuantity = async record => {
	const materialId = record.material_id || record.type;
	if (materialId) {
		const supplyOrderMaterialInfos = await post(`supplyOrder/materials`, {
			contract_ids: JSON.stringify(contractlist.value.map(item => item.id)),
			material_ids: JSON.stringify([materialId])
		});
		const supplyOrderMaterialInfos2MaterialId = supplyOrderMaterialInfos.reduce((target, item) => {
			if (!target[item.material.id]) {
				target[item.material.id] = 0;
			}
			target[item.material.id] = add([target[item.material.id], item.ys_quantity || 0]);
			return target;
		}, {});
		record.contractQuantity = subtract([contractInfo.value[materialId].quantity, supplyOrderMaterialInfos2MaterialId[materialId]]);
	}
};

const changeFangliang = record => {
	if (record.fangliang > record.contractQuantity) {
		proxy.$message.error("预计浇筑方量不能超过合同剩余量");
		record.fangliang = record.contractQuantity;
	}
	if (!record.fangliang) {
		record.fangliang = null;
	}
};
const modalTitle = computed(() => {
	return `${optType.value === 1 ? "新增" : optType.value === 2 ? "修改" : "查看"}商砼申请单`;
});

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.company_id) searchState.company_id = parseInt(query.company_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.code) searchState.code = query.code;
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}
const formRef = ref();
const { proxy } = getCurrentInstance();
const saveShangtong = () => {
	formRef.value.validate().then(() => {
		proxy.$message.destroy();

		const params = { ...formState.value };
		// 判断当前项目是否有合同
		if (!contractlist.value.length) {
			proxy.$message.error("当前项目尚未绑定合同");
			return;
		}

		// 检查数量是否超过所有合同
		if (!contractInfo.value[params.type]) {
			proxy.$message.error("请选择砼标号");
			return;
		}
		if (params.fangliang > contractInfo.value[params.type].quantity) {
			proxy.$message.error("浇筑方量不能超过合同数量");
			return;
		}

		params.material_id = params.type;
		params.type = contractInfo.value[params.type].model;
		params.contract_ids = contractlist.value.map(item => item.id).join(",");

		const gonghao_id = params.use_position.split("-")[1];
		let part = params.use_position.split("-").slice(-1)[0];
		if (gonghao_id === part) {
			part = null;
		}
		params.gonghao_id = gonghao_id;
		params.part = part;
		post("shangtong/save", params)
			.then(() => {
				proxy.$message.success("提交成功", 1);
				visible.value = false;

				initData();
				localStorage.removeItem("shangtong-save");
			})
			.catch(err => {
				proxy.$message.error(err.message);
			});
	});
};
const deleteShangtong = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的记录吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("shangtong/delete", { id }).then(() => {
				proxy.$message.success("删除成功");
				initData();
			});
		}
	});
};
const nullifyPurchase = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要作废${typeof id === "number" ? "当前" : "选中"}的记录吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("shangtong/invalid", { id }).then(() => {
				proxy.$message.success("记录作废成功");
				initData();
			}).catch((err) => {
				proxy.$message.warning(err);
			});
		}
	});
};
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}

:deep(.ant-input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

:deep(.ant-input-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

:deep(.ant-select-disabled.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

:deep(.ant-picker-input > input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	// border: 1px solid #d9d9d9;
}

//.ant-picker.ant-picker-disabled
:deep(.ant-picker.ant-picker-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	// border: 1px solid #d9d9d9;
}

.cache-btn {
	background-color: #0d9424;
	color: #fff;
}
</style>
<style lang="scss">
.table-striped{
	td{
		background-color: #d8d7d7;
	}
}
</style>
